﻿using System;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

using SWE4.Data.EmbeddedSensorCloud.DTO.Response;
using EmbeddedSensorCloud.HTTP;
using Newtonsoft.Json;

namespace EmbeddedSensorCloud.Plugin.MicroERP
{
    public class GetInvoiceCommand : ICommand
    {
        #region Fields

        IInvoiceDAO _InvoiceDao;
        JsonSerializerSettings _JsonSettings;

        #endregion

        #region Constructor

        public GetInvoiceCommand(IInvoiceDAO invoiceDao, JsonSerializerSettings jsonSettings)
        {
            this._InvoiceDao = invoiceDao;
            this._JsonSettings = jsonSettings;
        }

        #endregion

        #region ICommand

        public bool CanExecute(Request param)
        {
            return (param.Method.ToUpperInvariant() == "GET" &&
                    Regex.IsMatch(param.Url, @"^/api/invoice/[0-9]+$", RegexOptions.IgnoreCase));
        }

        public ResponseEntity Execute(Request param)
        {
            uint id;
            string[] urlParts = param.Url.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            if (urlParts.Length != 3 || !uint.TryParse(urlParts[2], out id))
            { throw new BadRequestException(); }

            InvoiceResponseModel model = this._InvoiceDao.Read(id);
            string returnString = JsonConvert.SerializeObject(model, this._JsonSettings);

            return new ResponseEntity(Encoding.UTF8.GetBytes(returnString), HttpStatusCode.OK);
        }

        #endregion
    }
}
